﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using WorldMapBase;
using WorldMapBase.Tile.Pool;
using Yoozoo.Managers.ResourceManagerV2.Runtime;
using Object = UnityEngine.Object;

public class HudRageEffectPool : ObjectPool<HudRageEffect>
{
    private GameObject prefab;
    private ResLoader _resLoader;
    private static string assetPath = "Assets/ResourcesAssets/Prefabs/Effect/UI/sfx_ui_nuqi.prefab";
    private Transform root;
    public bool InitComplete = false;
    public int initNum;
    
    public HudRageEffectPool(int initNum, int capacity, Transform poolRoot,
        bool enableAutoShrink, int idleMaxCount, int frameShrinkCount,float shrinkIntervalTime) 
        : base(capacity,enableAutoShrink,idleMaxCount,frameShrinkCount,shrinkIntervalTime)
    {
        _resLoader = ResLoader.Alloc();
        this.initNum = initNum;

        string rootName = "[HudEffectObjectPool]";
        var rootObject = new GameObject(rootName);
        root = rootObject.transform;
        root.SetParent(poolRoot);
    }

    public void StartLoad(int initNum,Action<string, bool> funcCallBack)
    {
        _resLoader.Add2Load(assetPath, (success, name, asset) =>
        {
            if (success)
            {
                prefab = asset as GameObject;
                OnInitAsync(initNum);
                InitComplete = true;
            }
            if (funcCallBack != null)
            {
                funcCallBack.Invoke(assetPath, success);
            }
        }).Load();
    }
    
    protected override HudRageEffect ConstructItem()
    {
        if (prefab == null)
        {
            Debug.LogErrorFormat("Prefab {0} is not ready", assetPath);
            return null;
        }

        var go = Object.Instantiate(prefab, root);
        go.transform.SetParent(root);
        go.transform.position = GlobalValue.INVISIBLE_POSITION;
        go.SetActive(true);
        HudRageEffect effectRoot = go.GetComponent<HudRageEffect>();
        return effectRoot;
    }
    
    protected override void BeforeRecover(HudRageEffect obj)
    {
        var objTransform = obj.transform;
        objTransform.SetParent(root);
        objTransform.position = GlobalValue.INVISIBLE_POSITION;

        obj.RecoverRage();
    }
    
    public void Dispose()
    {
        if (_resLoader != null)
        {
            _resLoader.Recycle2Cache();
            _resLoader = null;
        }

        prefab = null;
        Destroy();
        if (root != null)
        {
            Object.Destroy(root.gameObject);
            root = null;
        }
    }
}
